<template>
    <main class="box">
        <van-icon :name="!isSpeak ? 'volume-o' : 'apps-o'" @click="changeSpeak(!isSpeak)" />
        <template v-if="isSpeak">
            <div class="speak gray" v-if="loading">按住说话</div>
            <div class="speak" v-else @touchstart="startLongPress" @touchend="endLongPress"
                @touchcancel="cancelLongPress">按住说话</div>
        </template>
        <div class="speak" v-else>
            <van-field v-model="recognitionValue" placeholder="请输入识别内容" :disabled="loading" />
        </div>
        <div v-if="!isSpeak"><van-icon name="share-o" @click="sendMassage" /></div>
        <!-- <div v-else>
            <van-icon name="photograph" />
            <van-icon name="add-o" />
        </div> -->
        <van-dialog :overlay="false" v-model:show="dialogShow" title="语音识别" show-cancel-button @confirm="confirm">
            <van-field v-model="discernText" :rows="6" type="textarea" placeholder="顶部对齐" label-align="top" />
        </van-dialog>

    </main>
</template>
<script setup>
import { showFailToast } from 'vant';
import { onDeactivated, onMounted, ref } from 'vue';
const emit = defineEmits(['sendMassage', 'sendVoiceMessage']);
defineProps({
    loading: Boolean
})

const recognitionValue = ref('')
const isSpeak = ref(true)
const changeSpeak = (value) => {
    isSpeak.value = value
}
const sendMassage = () => {
    if (recognitionValue.value == "") {
        showFailToast('请输入内容');
        return
    }
    emit('sendMassage', recognitionValue.value)
    recognitionValue.value = ""
}
const discernText = ref('')

const confirm = () => {
    dialogShow.value = false
    emit('sendMassage', discernText.value)
}
const dialogShow = ref(false)
//语音方面代码
let recorder;
let speechRecognizer;
let isCanSendData = false;
let isCanStop;
const params = {
    signCallback: signCallback, // 鉴权函数 用户提供鉴权函数，不传则为null
    // 用户参数
    secretid: config.secretId,
    appid: config.appId,
    // 实时识别接口参数
    engine_model_type: '16k_zh', // 引擎
    voice_format: 1,
    // 以下为非必填参数，可跟据业务自行修改
    hotword_id: '08003a00000000000000000000000000',
    needvad: 1,
    filter_dirty: 1,
    filter_modal: 1,
    filter_punc: 1,
    convert_num_mode: 1,
    word_info: 2
}

const speakStart = () => {
    discernText.value = ""
    dialogShow.value = true
    let resultText = '';

    speechRecognizer = null;
    isCanSendData = false;
    // 获取录音数据
    recorder = new WebRecorder();
    recorder.OnReceivedData = (res) => {
        if (isCanSendData) {
            // 发送数据
            speechRecognizer.write(res);
        }
    };
    // 录音失败时
    recorder.OnError = (err) => {
        console.log(err);
        recorder.stop();
    };
    recorder.start();

    if (!speechRecognizer) {
        speechRecognizer = new SpeechRecognizer(params);
    }

    // 开始识别
    speechRecognizer.OnRecognitionStart = (res) => {
        console.log('开始识别', res);
        isCanSendData = true;
        isCanStop = true;

    };
    // 一句话开始
    speechRecognizer.OnSentenceBegin = (res) => {
        console.log('一句话开始', res);
    };
    // 识别变化时
    speechRecognizer.OnRecognitionResultChange = (res) => {
        console.log('识别变化时', res);
        const currentText = `${resultText}${res.result.voice_text_str}`;
        discernText.value = currentText
    };
    // 一句话结束
    speechRecognizer.OnSentenceEnd = (res) => {
        console.log('一句话结束', res);
        resultText += res.result.voice_text_str;
    };
    // 识别结束
    speechRecognizer.OnRecognitionComplete = (res) => {
        console.log('识别结束', res);
        isCanSendData = false;
    };
    // 识别错误
    speechRecognizer.OnError = (res) => {
        console.log('识别失败', res);
        isCanSendData = false;
    };
    // 建立连接
    speechRecognizer.start();
}
const speakEnd = () => {
    recorder.stop();
    if (isCanStop) {
        speechRecognizer.stop();
    }
}
const longPressTimeout = ref(null)
function startLongPress() {
    // 设置长按超时
    longPressTimeout.value = setTimeout(() => {
        //this.$emit('longpress');
        speakStart()
    }, 200); // 长按500毫秒触发
}
function endLongPress() {
    speakEnd()
    // 清除长按超时
    clearTimeout(longPressTimeout.value);
    longPressTimeout.value = null;
}
function cancelLongPress() {
    // 清除长按超时
    clearTimeout(longPressTimeout.value);
    longPressTimeout.value = null;
}
onMounted(() => {
    navigator.mediaDevices.getUserMedia({ audio: true });
})

defineExpose({
    changeSpeak
})

</script>
<style lang="scss" scoped>
.box {
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 50px;
    width: 100vw;
    padding: 0 0 30px 0;
    background: rgb(239, 239, 239);
    font-size: 22px;

    .speak {
        width: 80%;
        height: 40px;
        line-height: 40px;
        text-align: center;
        background: #fff;
        border-radius: 20px;
        font-size: 18px;
    }
    .gray {
        color: #c8c9cc;
    }
}
</style>